// Okay I admit the code is ugly...
if (typeof console === "undefined" || typeof console.log === "undefined") { //Fix IE window.console bug
    console = {};
    console.log = function () {
    };
}
var global = {
    "boards": [],
    labels: [],
    "checklists": [],
    "topCards": [],
    "cards": [],
    "lists": [],
    "members": [],
    boardIndex: 0,
    labelIndex: 0,
    boardList:[],
    headerColors:["style='background:#00B050'","style='background:#000000;color:#FFFFFF'","style='background:#C00000;color:#FFFFFF'","style='background:#7030A0;color:#FFFFFF'","style='background:#FF00FF;color:#FFFFFF'","style='background:#FFC000"],
    bodyRowColors:["style='background:#BDD7EE'","style='background:#C6E0B4'","style='background:#757171;color:#FFFFFF'","style='background:#9BC2E6'","style='background:#FFE699'","style='background:#ACE7E9'"]
};
global.init = function () {
    global.boards = [];
    global.checklists = [];
    global.topCards = [];
    global.cards = [];
    global.lists = [];
    global.members = [];
    global.boardList=[];
};
$(document).ready(function () {
    var defaultOptions = {
        scope: {
            write: false
        },
        success: initDoc
    };
    if (typeof Trello === "undefined") {
        $("#view").html("<h1>Connection to Trello API is broken, Please <a href='javascript:window.reload();'>Reload</a></h1>");
    }

    Trello.authorize(_.extend({}, defaultOptions, {// Authentication
        interactive: false
    }));

    if (!Trello.authorized()) {
        return Trello.authorize(defaultOptions);
    }

    $(window).bind("hashchange", router);
});
//授权成功执行该方法
var initDoc = function () {
    if (!Trello.authorized()) return Trello.authorize(defaultOptions);
    //看板选项 获取所有打开的看板
    Trello.get('/members/me', {boards: "open", organizations: "all"}, function (me) {
        window.myself = me;
        router();
    }, function (xhr) {
        if (xhr.status == 401) {
            Trello.deauthorize();
            Trello.authorize(defaultOptions);
        } else {
            $("#view").html("<h1>Connection to Trello API is broken, Please <a href='javascript:reload();'>Reload</a></h1>");
        }
    });
};

var router = function () {

    var hash = location.hash.replace("#", "");
    //如果hash不为空，显示所有的卡片，看板的
    if (hash !== "") {
        getBoard(hash);
    } else {
        //如果hash为空，则显示 看板列表
        if (window.myself) {
            listBoards();
        } else {
            initDoc();
        }
    }
};

var listBoards = function () {
    if (!myself.orgBoards) { // Not initiated yet
        var categories = _.groupBy(myself.boards, function (board) { // Categories Boards
            var id = board.idOrganization ? board.idOrganization : "";
            return id;
        });
        var orgList = _.groupBy(myself.organizations, function (org) { // Map orgId-orgName
            return org.id;
        });

        myself.orgBoards = _.map(categories, function (value, key) { // Create Array of Organizations containing Array of Boards
            var list = {};
            list.boards = value;
            if (key === "" || key === null) {
                list.name = "Personal";
            } else if (!orgList.hasOwnProperty(key)) {
                list.name = "External Organization";
            } else {
                list.name = orgList[key][0].displayName
            }
            return list;
        });
    }
    myself.orgBoards.forEach(function (e) {
        e.boards.forEach(function (board) {
            e.orgId = board.idOrganization;
        });
    });
    $("#view").empty();
    var template = getTemplate("report_list.tpl.html");
    var str = Mustache.render(template, myself);
    $("#view").html(str);
    $("#boardlist").masonry({
        itemSelector: '.list'
    });

};

var getBoard = function (board) {
    $("#view").empty();
    $("#view").html("<h1>Loading ...</h1>");
    Trello.get("/boards/" + board, {cards: "open", lists: "open", checklists: "all", members: "all"}, function (board) {
        $("#view").html("<h1>Loading ...OK!!</h1>");
        window.doc = board; //debug
        window.title = board.name;
        _.each(board.cards, function (card) { //iterate on cards
            _.each(card.idChecklists, function (listId) { //iterate on checklists
                var list = _.find(board.checklists, function (check) { //Find list
                    return check.id == listId;
                });
                if (!list) {
                    console.log("ERROR:" + listId + " not found");
                    return;
                }
                list.doneNumber = 0;
                list.totalNumber = list.checkItems.length || 0;
                _.each(list.checkItems, function (item) { //Check complete
                    if (item.state == "complete") {
                        list.doneNumber++;
                        item.complete = true;
                    } else item.complete = false;
                });
                list.done = (list.doneNumber == list.totalNumber);
                var template = "<div><b>{{name}}</b> <span class='show right {{#done}}green{{/done}}'>{{doneNumber}}/{{totalNumber}}</span></div><ul>{{#checkItems}}<li>{{#complete}}<del>{{/complete}}{{name}}{{#complete}}</del>{{/complete}}</li>{{/checkItems}}</ul>";
                var str = Mustache.render(template, list);

                card.checklist = card.checklist || []; //Make array
                card.checklist.push(str);
            });//iterate on checklists

            card.members = _.map(card.idMembers, function (id) { // iterate on members
                var member = _.find(board.members, function (m) {
                    return m.id == id;
                });
                return member.username;
            });// iterate on members
        });//iterate on cards

        // Second Init Cards
        var listofcards = _.groupBy(board.cards, function (card) {
            return card.idList;
        });
        _.each(board.lists, function (list) {
            list.cards = listofcards[list.id];
            list.size = list.cards ? list.cards.length : 0;
            list.show = (list.size > 0);
        });

        // Date function
        board.formatDate = function () {
            return function (text) {
                var date;
                switch (text) {
                    case "":
                        return "None";
                    case "now":
                        date = new Date();
                        break;
                    default:
                        date = new Date(text);
                }
                return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            };
        };
        board.formatComments = function () {
            var converter = new Showdown.converter();
            return converter.makeHtml;
        };
        //
        // Start Rendering
        board.displayColumns = ["名称", "对接进度", "预计上线时间", "实际上线时间", "人员", "Labels", "备注"];
        var htmltemplate = "<h1><span id='download'></span><span id='trello-link'></span><span id='printme'></span>{{name}} <span class='right'>{{#formatDate}}now{{/formatDate}}</span></h1>{{#lists}}<table><caption><h2>{{name}} <span class='show right'>{{size}}</span></h2></caption>{{#show}}<col width='20%' /><col width='30%' /><col width='5%' /><col width='25%' /><col width='5%' /><col width='10%' /><col width='5%' /><thead><tr>{{#displayColumns}}<th scope='col'>{{.}}</th>{{/displayColumns}}</tr></thead>{{/show}}<tbody>{{#cards}}<tr><td scope='row'><b>{{name}}</b></td><td><div class='comments'>{{#formatComments}}{{desc}}{{/formatComments}}</div></td><td>{{#formatDate}}{{due}}{{/formatDate}}</td><td>{{#checklist}}<div>{{{.}}}</div>{{/checklist}}</td><td>{{#members}}<div>{{.}}</div>{{/members}}</td><td>{{#labels}}<div class='show {{color}}'>{{name}}&nbsp;</div>{{/labels}}</td><td>{{badges.votes}}</td></tr>{{/cards}}</tbody></table>{{/lists}}";
        var csvtemplate = "";//TODO

        var str = Mustache.render(htmltemplate, board);
        $("#view").html(str);

        // Download Button
        var download = "<!DOCTYPE html><html><head><meta charset='utf-8' /><title>" + board.name + "</title><style>" + $("style").text() + "</style></head><body>" + str + "</body></html>";
//this may work for firefox using application/data
//location.href="data:text/html;charset=utf-8,"+encodeURIComponent(download);
        var button1 = $("#download");
        button1.addClass("downloader");
        button1.text("Save HTML");
        button1.click(function () {
            console.log("saving..");
            var bb = new BlobBuilder();
            bb.append(download);
            var filesaver = saveAs(bb.getBlob("text/html;charset=utf-8"), board.name + "_" + board.formatDate()('now') + ".html");
        });
        var button2 = $("#trello-link");
        button2.addClass("downloader");
        button2.text("Trello");
        button2.click(function () {
            location = board.url;
        });
        var button3 = $("#printme");
        button3.addClass("downloader");
        button3.text("Print");
        button3.click(function () {
            print();
        });
    });
};
function getTemplate(url) {
    var html = $.ajax({
        url: url,
        async: false
    }).responseText;
    return html;
}
function gotoForm(orgId) {
    global.init();
    var i = 0;
    myself.orgBoards.forEach(function (e) {
        var isThisOrg = false;
        e.boards.forEach(function (board) {
            if (!isThisOrg) {
                if (board.idOrganization == orgId) {
                    isThisOrg = true;
                }
            }
            if (isThisOrg) {
                global.boardList.push(board.id);
            }


        });
        if(isThisOrg)
        {
            return;
        }

    });
    myTrello.getBoard(global.boardList[ global.boardIndex]);
    console.log("-----------------------------执行完毕");


}
function exportExcel()
{
    //html table 转 excel
    //e.preventDefault();

    //getting data from our table
    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('tableDiv');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');

    var a = document.createElement('a');
    a.href = data_type + ', ' + table_html;
    a.download = 'exported_table_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
    a.click();
}